package com.efounder.chat.http;

import android.content.Context;

import com.efounder.chat.R;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.LogoutEvent;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.AppContext;
import com.utilcode.util.LogUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;

/**
 * 获取eth用户公钥 地址
 */
public class OpenEthRequest {
    private static final String TAG = "OpenEthRequest";


    /**
     * 获取eth用户信息
     *
     * @param context
     * @param userId   用户IMID
     * @param listener
     */
    public static void getUserEthByImUserId(Context context, int userId, EthRequestListener listener) {
        getUserEthByImUserId(context, userId, listener, false);
    }

    /**
     * @param context
     * @param userId               用户imuserId
     * @param listener             回调
     * @param forcerequestByServer 是否强制从服务器获取
     */
    public static void getUserEthByImUserId(Context context, int userId, EthRequestListener listener, boolean forcerequestByServer) {

//        if (forcerequestByServer) {
//            requestServer(context, userId, listener);
//            return;
//        }
        requestServer(context, userId, listener);
    }

    /**
     * 查询一个用户
     *
     * @param context
     * @param userId
     * @return
     */
    private static User getEthUserByDb(Context context, int userId) {
        User user = WeChatDBManager.getInstance().getOneUserById(userId);
        return user;
    }

    /**
     * 请求臧老师服务器，获取通讯公钥
     *
     * @param context
     * @param userId
     * @param listener
     */
    private static void requestServer(final Context context, final int userId, final EthRequestListener listener) {

        String baseUrl = EnvironmentVariable.getProperty("TalkChainUrl") + "/tcserver/user/getUserByIMUserId";
        HashMap<String, String> map = new HashMap<>();
        map.put("otherIMUserId", userId + "");
        map.put("access_token", EnvironmentVariable.getProperty("tc_access_token"));
        JFCommonRequestManager.getInstance(context).requestGetByAsyn(TAG, baseUrl, map, new JFCommonRequestManager.ReqCodeCallBack<String>() {

            @Override
            public void onReqSuccess(String result) {
                // HttpRequestStatusUtils.remove("tc_request_user" + userId);
                // {"result":"success","user":{"ethAddress":"0x66DbaF2d30549aAFed0E468c85da14CBA7E0eA54",
                //   "ethPublicKey":"0x045d1de50d93b86efb04703f4c7b450e91ce501ed704d450073dea931655105fceee5d5e07b203b52c916985ab8bd74c758bd07786f9f747304fe9c788c0c404ad","fromInviteCode":"QU14Q9","imUserId":181540,"inviteCode":"RPY38Y","inviteCodeUseCount":0,"userId":"15898908031","userIdMd5":"D74FC5DA5D3AEB6EF81684ABAB414842","userName":"q"}}
                try {
                    net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                    String ethAddress = null;
                    String ethPublicKey = null;
                    String RSAPublicKey = null;
                    if (jsonObject.containsKey("result") && jsonObject.getString("result").equals("success")) {
                        net.sf.json.JSONObject jsonObject1 = jsonObject.getJSONObject("user");
                        if (jsonObject1.containsKey("ethAddress")) {
                            ethAddress = jsonObject1.getString("ethAddress");
                            if (ethAddress != null && !ethAddress.toLowerCase().startsWith("0x") && !ethAddress.equals("")) {
                                ethAddress = "0x" + ethAddress;
                            }
                        }
                        if (jsonObject1.containsKey("ethPublicKey")) {
                            ethPublicKey = jsonObject1.getString("ethPublicKey");
                        }
                        if (jsonObject1.containsKey("comPublicKey")) {
                            RSAPublicKey = jsonObject1.getString("comPublicKey");
                        }

                        User user = getEthUserByDb(context, userId);
                        user.setWalletAddress(ethAddress);
                        user.setPublicKey(ethPublicKey);
                        user.setRSAPublicKey(RSAPublicKey);
                        user.setAllowStrangerChat(jsonObject1.optInt("disableStrangers", 0) == 0 ? true : false);
                        user.setReMark(jsonObject1.optString("note", user.getReMark()));
                        user.setWeixinQrUrl(jsonObject1.optString("weChatQRCode", user.getWeixinQrUrl()));
                        user.setZhifubaoQrUrl(jsonObject1.optString("aliPayQRCode", user.getZhifubaoQrUrl()));

                        if (listener != null) {
                            listener.onSuccess(ethAddress, ethPublicKey, RSAPublicKey);

                        }
                        //兼容 返回user 多个字段
                        if (listener != null && listener instanceof EthUserRequestListener) {
                            ((EthUserRequestListener) listener).onSuccess(user);

                        }
                        //weChatDBManager.insertUserTable(user);
                    }

//                    else {
//                        if (jsonObject.optString("msg", "").equals("invalid_token")) {
//                            //token 失效，刷新token 使用反射的方式
//                            try {
//                                ReflectUtils reflectUtils = ReflectUtils.reflect("com.pansoft.openplanet.util.TCRequestUtil");
//                                reflectUtils.method("refreshToken", TAG, null);
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                            if (listener != null) {
//                                listener.onFail(ResStringUtil.getString(R.string.wechatview_request_fail_please));
//                            }
//                            return;
//                        }
//
//                        if (listener != null) {
//                            listener.onFail(jsonObject.optString("msg", ""));
//                        }
//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    if (listener != null) {
                        listener.onFail("");
                    }
                }

            }

            @Override
            public void onReqFailed(String errorMsg) {
            }

            @Override
            public void onReqFailed(int errorCode, String errorMsg) {
                if (listener != null) {
                    //listener.onFail("");
                    LogUtils.e("请求失败，从数据库中查询");
                    User user = getEthUserByDb(context, userId);
                    listener.onSuccess(user.getWalletAddress(), user.getPublicKey(), user.getRSAPublicKey());
                }

                //兼容 返回user 多个字段
                if (listener != null && listener instanceof EthUserRequestListener) {
                    User user = getEthUserByDb(context, userId);
                    ((EthUserRequestListener) listener).onSuccess(user);
                }
                //todo 针对区块链应用，如果errorcode =400 表示用户登录失效，需要重新登录 yqs
                if (errorCode == 400 && EnvironmentVariable.getProperty(KEY_SETTING_APPID, "").equals(AppContext.getInstance()
                        .getString(R.string.special_appid))) {
                    //发送弹框提示用户
                    EventBus.getDefault().post(new LogoutEvent(LogoutEvent.TYPE_LOGIN_OUT_OF_DATE));

                }
            }

        });

    }

    public static void cannelRequest() {
        JFCommonRequestManager.getInstance(AppContext.getInstance()).cannelOkHttpRequest(TAG);
    }

    public interface EthRequestListener {
        void onSuccess(String ethAddress, String publicKey, String RSAPublicKey);

        void onFail(String error);
    }


    //之前返回三个字段不够用，返回user
    public interface EthUserRequestListener extends EthRequestListener {
        void onSuccess(User user);
    }
}
